﻿using Infrastructure.Dao;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WsdShop.Model;
using Infrastructure.Tool;
using WsdShop.IService;
using WsdShop.Model.ViewModels;
using Infrastructure.Pub;
using ServiceStack;
using WsdShop.Model.SearchModels;
using Infrastructure;

namespace WsdShop.Service
{
    public class UserInfoService : IUserInfoService
    {

        public CacheUserInfo GetUserInfo(int id)
        {
            using (var _db = DbConfig.GetInstance())
            {
                var user = _db.Queryable<UserInfo>().FirstOrDefault(t => t.Id == id);
                if (user == null)
                {
                    return null;
                }
                var cacheuser = user.ConvertTo<CacheUserInfo>();

                var group = _db.Queryable<UserGroup>().SingleOrDefault(t => t.Id == user.GroupId);
                if (group != null && group.Id > 0)
                {
                    cacheuser.IsAdmin = group.IsAdmin;
                    cacheuser.GroupName = group.GroupName;
                }

                var userrole = _db.Queryable<UserGroupRole>().Where(t => t.UserGroupId == user.GroupId).ToList();
                if (userrole != null && userrole.Count > 0)
                {
                    var userroles = new List<UserRole>();
                    userrole.ForEach(m => userroles.Add(new UserRole { MenuRole = m.MenuId.ToString(), OperateRoles = m.OperateRoles }));
                    cacheuser.UserRoles = userroles;
                }

                var wxconfig = _db.Queryable<WxConfig>().SingleOrDefault(m => m.Id > 0);
                if (wxconfig != null)
                {
                    cacheuser.AppId = wxconfig.AppId;
                    cacheuser.AppSecret = wxconfig.AppSecret;
                }

                return cacheuser;
            }
        }

        public CacheUserInfo GetUserInfo(string userName)
        {
            using (var _db = DbConfig.GetInstance())
            {
                var user = _db.Queryable<UserInfo>().FirstOrDefault(t => t.UserName == userName);
                if (user == null)
                {
                    return null;
                }
                var cacheuser = user.ConvertTo<CacheUserInfo>();

                var group = _db.Queryable<UserGroup>().SingleOrDefault(t => t.Id == user.GroupId);
                if (group != null && group.Id > 0)
                {
                    cacheuser.IsAdmin = group.IsAdmin;
                }

                var userrole = _db.Queryable<UserGroupRole>().Where(t => t.UserGroupId == user.GroupId).ToList();
                if (userrole != null && userrole.Count > 0)
                {
                    var userroles = new List<UserRole>();
                    userrole.ForEach(m => userroles.Add(new UserRole { MenuRole = m.MenuId.ToString(), OperateRoles = m.OperateRoles }));
                    cacheuser.UserRoles = userroles;
                }

                return cacheuser;
            }
        }

        /// <summary>
        /// 验证用户名和密码
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool CheckUserInfo(string userName, string password)
        {
            using (var _db = DbConfig.GetInstance())
            {
                var user = _db.Queryable<UserInfo>().FirstOrDefault(t => t.UserName == userName);
                if (user != null && user.Password == password)
                {
                    return true;
                }
                return false;
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="pwssword">原密码</param>
        /// <param name="newPassword">新密码</param>
        /// <returns></returns>
        public bool UpdatePassword(int userId, string pwssword, string newPassword)
        {
            using (var _db = DbConfig.GetInstance())
            {
                var user = GetUserInfo(userId);
                if (user == null)
                {
                    throw new Exception("用户不存在");
                }
                if (user.Password != pwssword)
                {
                    throw new Exception("原密码不正确");
                }

                user.Password = Generator.MD5(newPassword);

                return _db.Update<UserInfo>(user);
            }
        }

        public List<UserInfo> GetUserList(string where = "")
        {
            using (var _db = DbConfig.GetInstance())
            {
                var list = _db.Queryable<UserInfo>().Where(where).ToList();
                return list;
            }
        }

        public CacheUserInfo GetCacheUser()
        {
            string uid = Generator.GetCookie(PubConst.CookieUserKey);
            if (!uid.IsNullOrEmpty())
            {
                string uniqueKey = string.Format(PubConst.CacheUserKey, uid);
                var user = CacheManager<CacheUserInfo>.GetInstance()[uniqueKey];
                if (!(user != null && user.Id > 0)||user.GroupName.IsNullOrEmpty())
                {
                    user = GetUserInfo(uid.ObjToInt());
                    CacheManager<CacheUserInfo>.GetInstance().Add(uniqueKey, user,600);
                }
                return user;
            }

            return new CacheUserInfo();
        }

        public void SetCacheUser(int uid)
        {
            string uniqueKey = string.Format(PubConst.CacheUserKey, uid.ToString());
            var user = GetUserInfo(uid);

            CacheManager<CacheUserInfo>.GetInstance().Add(uniqueKey, user, 600);
        }

        public List<UserViewModel> GetUserList(UserSearchModel search, out int total)
        {
            using (var _db = DbConfig.GetInstance())
            {
                _db.CurrentFilterKey = "";
                Sqlable sable = _db.Sqlable().From<UserInfo>("u").Join<UserGroup>("g", "u.GroupId", "g.Id", JoinType.Left);
                sable.Where(" u.IsDeleted=0 ");
                if (!search.Keywords.IsNullOrEmpty())
                {
                    sable.Where(" (u.UserName like @userName or u.RealName like @realName or u.Phone like @phone) ");
                }

                if (search.UserGroupId > 0)
                {
                    sable.Where(" u.GroupId=@groupId ");
                }

                if (search.UserState > -1)
                {
                    sable.Where(" u.UserState=@userState ");
                }

                var pars = new { userName = "%" + search.Keywords + "%", realName = "%" + search.Keywords + "%", phone = "%" + search.Keywords + "%", groupId = search.UserGroupId, userState = search.UserState };
                total = sable.Count(pars);
                var list = sable.SelectToPageList<UserViewModel>("u.*,g.IsAdmin,g.GroupName", "u." + search.OrderByFields, search.Skip / search.Take + 1, search.Take, pars);
                return list;
            }
        }

        public Result UpdateUserPassWord(int Id, string NewPassword, int currentUserId, string OldPassword = "")
        {
            using (var Db = DbConfig.GetInstance())
            {
                var user = Db.Queryable<UserInfo>().SingleOrDefault(m => m.Id == Id);
                if (user == null || user.Id == 0)
                {
                    return Result.Failure("该用户不存在");
                }

                if (!OldPassword.IsNullOrEmpty())
                {
                    if (user.Password != Generator.MD5(OldPassword))
                    {
                        return Result.Failure("原密码不正确");
                    }
                }

                user.Password = Generator.MD5(NewPassword);
                user.EditTime = DateTime.Now;
                user.EditUserId = currentUserId;
                if (Db.Update(user))
                {
                    return Result.Success();
                }
                return Result.Failure("修改失败");
            }
        }

        public Result DelUser(int Id, int currentUserId)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var user = Db.Queryable<UserInfo>().SingleOrDefault(m => m.Id == Id);
                if (user == null || user.Id == 0)
                {
                    return Result.Failure("该用户不存在");
                }
                user.IsDeleted = true;
                user.EditUserId = currentUserId;
                user.EditTime = DateTime.Now;
                if (Db.Update(user))
                {
                    return Result.Success();
                }
                return Result.Failure("操作失败");
            }
        }

        public UserInfo GetUserInfoById(int Id)
        {
            using (var Db = DbConfig.GetInstance())
            {
                return Db.Queryable<UserInfo>().SingleOrDefault(m => m.Id == Id);
            }
        }

        public Result UserEditSubmit(UserInfo user, int currentUserId)
        {
            if (user == null)
            {
                return Result.Failure("传入参数有误");
            }

            using (var Db = DbConfig.GetInstance())
            {
                var isexist = Db.Queryable<UserInfo>().Where(m => m.UserName == user.UserName && m.Id != user.Id).Count();
                if (isexist > 0)
                {
                    return Result.Failure("该用户名已存在");
                }

                if (user.Id == 0)
                {
                    user.Password = Generator.MD5(user.Password);
                    user.AddUserId = currentUserId;
                    Db.Insert(user);
                }
                else
                {
                    user.EditTime = DateTime.Now;
                    user.EditUserId = currentUserId;
                    Db.Update(user);
                }
                return Result.Success();
            }
        }

        public Result ChangeUserState(int Id, int userState, int currentUserId)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var user = Db.Queryable<UserInfo>().SingleOrDefault(m => m.Id == Id);
                if (user == null || user.Id == 0)
                {
                    return Result.Failure("该用户不存在");
                }

                user.UserState = userState;
                user.EditTime = DateTime.Now;
                user.EditUserId = currentUserId;
                if (Db.Update(user))
                {
                    return Result.Success();
                }
                return Result.Failure("更新失败");
            }
        }

    }
}
